package com.jet.chat.dbquery;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class ChatQueryGetHistory extends ChatQueryAbstract {

	@Override
	protected ChatQueryResult main(Connection conn, ChatQueryParams chatQueryParams) throws Exception {
		int userId = ((ChatQueryGetHistoryParams) chatQueryParams).getUserId();
		String timestamp = ((ChatQueryGetHistoryParams) chatQueryParams).getTimestamp();
		
		ChatQueryGetHistoryResult result = new ChatQueryGetHistoryResult();
		
		PreparedStatement ps = conn.prepareStatement("select m.timestamp, u.username, m.channelname, m.pub, m.content from messages as m, isread as i, users as u where i.userid = ? and m.id = i.messageId and m.senderId = u.id and m.timestamp >= ?");
		ps.setInt(1, userId);
		ps.setString(2, timestamp);
		ResultSet results = ps.executeQuery();
		while(results.next()) {
			ChatQueryGetHistoryResultRaw raw = new ChatQueryGetHistoryResultRaw(
				results.getTimestamp(1),
				results.getString(2),
				results.getString(3),
				results.getInt(4),
				results.getString(5)
			);
			result.add(raw);
		}
		results.close();
		
		return result;
	}

}
